package com.slz3.business.frame.api.alipay;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.slz3.business.frame.api.tool.AppEnv;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * 支付宝支付
 *
 */
public class AlipayApi{
	/**
	 * 支付请求地址
	 */
	public static String payGateway = "https://mapi.alipay.com/gateway.do?";
	/**
	 * 编码方式
	 */
	public static String _input_charset = "utf-8";
	/**
	 * 签名加密方式
	 */
	public static String sign_type = "MD5";
	/**
	 * 合作者ID
	 */
	//public static String partner = "2088711988472850";
	public static String partner = AppEnv.getInstance().getStringProp("alipay.partner", "2018071460726101");
	/**
	 * 合作者安全交易验证码
	 */
	//public static String securityCode = "54gdyxve1zwlgyv272un47dixiwg8qq7";
	public static String securityCode =AppEnv.getInstance().getStringProp("alipay.security_code", "8wox5atoxcdy1647rfm68v9yozzwgf4j") ;
	
	public static String buildPayRequestURL(Map<String, String> params){
		StringBuilder sbUrl = new StringBuilder(payGateway);
        String tosign = getSignString(params);
        String sign = sign(tosign);
        if(null!=sign){
        	List<String> keys = new ArrayList<String>(params.keySet());
        	for (int i = 0; i < keys.size(); i++) {
				String key = keys.get(i);
				String value = params.get(key);
				try{
					value = URLEncoder.encode(value, _input_charset);
				}catch(Exception e){
					e.printStackTrace();
				}
				sbUrl.append(key + "=" + value);
				if (i<keys.size()) {
					sbUrl.append("&");
	            }
			}
        	sbUrl.append("&sign_type="+sign_type+"&sign="+sign);
        }
        String url = sbUrl.toString();
        System.out.println("URL："+url);
		return url;
	}
	
	public static String buildPayRequestHTML(Map<String, String> params){
		String html = "ERROR";
        String tosign = getSignString(params);
        String sign = sign(tosign);
        
        if(null!=sign){
        	params.put("sign_type", sign_type);
        	params.put("sign", sign);
        	
	        List<String> keys = new ArrayList<String>(params.keySet());
	        StringBuffer sbHtml = new StringBuffer();
	        sbHtml.append("<form id=\"alipaysubmit\" name=\"alipaysubmit\" action=\"" + payGateway + "_input_charset=" + _input_charset + "\" method=\"POST\">");
	
	        for(int i=0; i<keys.size(); i++) {
	        	String name = (String) keys.get(i);
	        	String value = (String) params.get(name);
	        	sbHtml.append("<input type=\"hidden\" name=\"" + name + "\" value=\"" + value + "\"/>");
	        }
	
	        //submit按钮控件请不要含有name属性
	        sbHtml.append("<input type=\"submit\" value=\"确定\" style=\"display:none;\"></form>");
	        sbHtml.append("<script>document.forms['alipaysubmit'].submit();</script>");
	        
	        html = sbHtml.toString();
        }
        System.out.println("HTML："+html);
        return html;
	}
	public static Map<String, String> buildPayRequestMap(Map<String, String> params){
		//String html = "ERROR";
		String tosign = getSignString(params);
		String sign = sign(tosign);
		
		if(null!=sign){
			params.put("sign_type", sign_type);
			params.put("sign", sign);
			params.put("action", payGateway + "_input_charset=" + _input_charset);
		}
		System.out.println(params.toString());
		return params;
	}
	
	private static String sign(String tosign) {
		String sign = null;
        if(sign_type.equalsIgnoreCase("MD5")) {
        	byte[] sbyte = null;
        	if(_input_charset == null || _input_charset.trim().length()==0){
        		sbyte = tosign.getBytes();
        	}
        	try {
        		sbyte = tosign.getBytes(_input_charset);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + _input_charset);
            }
        	if(sbyte!=null)sign = DigestUtils.md5Hex(sbyte);
        }
        System.out.println("Sign："+sign);
		return sign;
	}
	
	private static String getSignString(Map<String, String> params){
		List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        String tosign = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {
            	tosign += key + "=" + value;
            } else {
            	tosign += key + "=" + value + "&";
            }
        }
        tosign += securityCode;
        System.out.println("To Sign："+tosign);
        return tosign;
	}

}